using System;
using System.Collections.Generic;
using System.Web.Mvc;
using AutoMapper;
using SapaFinance.DTO;
using SapaFinance.Domain.Model;

namespace SapaFinance.OOMap.Helpers
{
    public class RequestToRequestDTOConvert : TypeConverter<Request, RequestDTO>
    {
        private readonly IMappingEngine _mappingEngine;

        public RequestToRequestDTOConvert(IMappingEngine mappingEngine)
        {
            _mappingEngine = mappingEngine;
        }

        protected override RequestDTO ConvertCore(Request request)
        {
            var dto = new RequestDTO();
            dto.UID = request.UID;
            dto.TaxRate = request.TaxRate.Value;
            dto.SelectedBudgetItem = request.BudgetItem.UID;
            dto.CreatedBy = request.CreatedBy.User.FullName;
            dto.Created = request.CreatedBy.DateTime;
            dto.ChangedBy= request.ChangedBy.User.FullName;
            dto.Changed = request.ChangedBy.DateTime;
            dto.Description = request.Description;
            dto.Payee = request.Payee.Name;
            if (request.Payer != null){
                dto.Payer = request.Payer.Name;
                dto.SelectedPayer = request.Payer.UID;
            }
            dto.SelectedPayee = request.Payee.UID;
            dto.Payment = request.Payment.Amount;
            dto.PaymentPeriod = request.PaymentPeriod;
            dto.PaymentPurpose = request.PaymentPurpose;
            dto.Number = request.Unique.ToString();
            dto.CfoName = request.Department.Name;
            dto.SelectedCfo = request.Department.UID;
            dto.IsAccepted = request.IsAccepted;
            dto.PaymentTypeName = request.PaymentType.Name;
            dto.SelectedAccount = GetAccount(request);
            dto.SelectedPaymentType = request.PaymentType.UID;
            dto.AccountList = _mappingEngine.Map<Account, IEnumerable<SelectListItem>>(request.PayeeAccount);
            dto.CurrencyDetail = _mappingEngine.Map<Account, CurrencyDetailDTO>(request.PayeeAccount);
            dto.PaidPercentByOrder = request.PaidPercentByOrder();
            return dto;
        }

        private static Guid? GetAccount(Request request)
        {
            if (request.PayeeAccount != null) return request.PayeeAccount.UID;
            var account = request.Payee.GetPrimaryAccount();
            return account != null ? account.UID : (Guid?) null;
        }
    }
}